import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:getwidget/getwidget.dart';
import 'package:intl/intl.dart';
import 'package:nb_utils/nb_utils.dart';
import 'package:pitchertools/common/extensions/datetime_extension.dart';
import 'package:pitchertools/dao/data_manager.dart';
import 'package:pitchertools/http/dio_http.dart';
import 'package:syncfusion_flutter_datepicker/datepicker.dart';
import 'package:velocity_x/velocity_x.dart';

import '../../../../http/api.dart';
import '../../../../models/fans_query_bean.dart';
import '../../index.dart';
import 'login_damai_dialog.dart';

class DetailsQueryFansMsgDialog extends GetView<QueryFansController> {
  DetailsQueryFansMsgDialog({required this.selectedIndex, super.key}) {}
  // 选中的索引
  final int selectedIndex;

  final controller = Get.find<QueryFansController>();

  /// 构建下拉菜单
  buildDropdownMenuItems(FansQueryBean selecedFansQueryBean) {
    List fansQueryApiMsgs = controller.state.fansQueryApiMsgsRx.value;

    var selectedFansQueryApiMsg = null;

    // print(fansQueryApiList);

    List<DropdownMenuItem> dropdownMenuItems = [];

    for (var i = 0; i < fansQueryApiMsgs.length; i++) {
      var item = DropdownMenuItem(
        value: fansQueryApiMsgs[i],
        child: Text(fansQueryApiMsgs[i]['queryApiName']),
      );
      dropdownMenuItems.add(item);
      if (selecedFansQueryBean.queryApiUrl ==
          fansQueryApiMsgs[i]['queryApiUrl']) {
        controller.state.selectedFansQueryApiMsg = fansQueryApiMsgs[i];
        selectedFansQueryApiMsg = controller.state.selectedFansQueryApiMsg;
      }
    }

    return Container(
      decoration: BoxDecoration(
        border: Border.all(color: Colors.black, width: 1.0),
        borderRadius: BorderRadius.circular(4.0),
      ),
      child: DropdownButton(
        value: selectedFansQueryApiMsg['queryApiName'] == null
            ? null
            : selectedFansQueryApiMsg,
        onChanged: (newValue) {
          //设置查询api
          controller.state.selectedFansQueryApiMsg = newValue;
          print(newValue);
          print(newValue.runtimeType);
        },
        items: dropdownMenuItems,
        hint: const Text("请选择查询类型"),
        underline: Container(),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    List fansQueryBeans = controller.state.fansQueryBeanListRx;
    FansQueryBean selecedFansQueryBean = fansQueryBeans[selectedIndex];

    final TextEditingController csNumberTEC =
        TextEditingController(text: selecedFansQueryBean.csNumber);
    final TextEditingController startDateTEC =
        TextEditingController(text: selecedFansQueryBean.startDate);
    final TextEditingController endDateTEC =
        TextEditingController(text: selecedFansQueryBean.endDate);

    final PickerDateRange selectedDateRange = PickerDateRange(
      DateTime.parse(selecedFansQueryBean.startDate),
      DateTime.parse(selecedFansQueryBean.endDate),
    );

    final DateRangePickerController dateRangePC = DateRangePickerController();

    controller.state.smsCode = "";

    return AlertDialog(
      title: const Text('详情').center(),
      content: SingleChildScrollView(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          //设置间隔为8
          children: [
            ListTile(
              title: SelectableText("客服号: ${selecedFansQueryBean.csNumber}"),
            ),
            ListTile(
              title: Obx(() {
                return SelectableText("code:${controller.state.smsCode}");
              }),
              leading: GFIconButton(
                type: GFButtonType.transparent,
                icon: const Icon(Icons.login),
                onPressed: () {
                  showDialog(
                    context: context,
                    barrierDismissible: true,
                    builder: (BuildContext context) => LoginDamaiDialog(),
                  );
                },
              ),
              trailing: GFIconButton(
                type: GFButtonType.transparent,
                icon: const Icon(Icons.sms),
                onPressed: () async {
                  SmartDialog.showLoading(clickMaskDismiss: true);
                  var queryParameters = {
                    "csUsername": selecedFansQueryBean.csNumber,
                    "pageNum": 1,
                    "pageSize": 15
                  };
                  var rp = await DioHttp.get(Api.DAMAI_GET_ACCOUNT_CHATS_API,
                      queryParameters: queryParameters);

                  print(rp);

                  if (rp == null || rp['code'] == 401) {
                    // SmartDialog.showToast(rp['msg'] ?? "获取聊天数据失败");
                    SmartDialog.showToast("请先点击左边登录账号");
                    return;
                  }
                  bool getSmsCodeFlag = false;
                  List chats = rp['chatInfo']['chatUsers']['rows'];
                  for (var i = 0; i < chats.length; i++) {
                    String content = chats[i]['content'];
                    //判断content内是不是有"Facebook 验证码"
                    if (content.contains("Facebook 验证码")) {
                      //获取content内的数字
                      RegExp pattern = RegExp(r'\d+'); // 匹配一个或多个数字
                      Match? match = pattern.firstMatch(content);

                      if (match != null) {
                        String verificationCode = match.group(0)!;
                        print('验证码是: $verificationCode');
                        controller.state.smsCode = verificationCode;
                      } else {
                        controller.state.smsCode = "未获取";
                      }
                      getSmsCodeFlag = true;
                      break;
                    }
                  }

                  if (!getSmsCodeFlag) {
                    controller.state.smsCode = "未获取";
                  }

                  SmartDialog.dismiss();
                },
              ),
            ),
            ListTile(
              title: SelectableText("客服姓名: ${selecedFansQueryBean.csName}"),
            ),
            ListTile(
              title: SelectableText("当天加粉: ${selecedFansQueryBean.addFansNow}"),
            ),
            ListTile(
              title:
                  SelectableText("当天重粉: ${selecedFansQueryBean.repeatFansNow}"),
            ),
            Obx(() => buildDropdownMenuItems(selecedFansQueryBean)),
            10.heightBox,
            SizedBox(
              height: 250,
              width: 250,
              child: SfDateRangePicker(
                view: DateRangePickerView.month,
                selectionMode: DateRangePickerSelectionMode.range,
                initialSelectedRange: selectedDateRange,
                controller: dateRangePC,
                onSelectionChanged: (dateRangePickerSelectionChangedArgs) {
                  if (dateRangePickerSelectionChangedArgs.value
                      is PickerDateRange) {
                    PickerDateRange pickerDateRange =
                        dateRangePickerSelectionChangedArgs.value;

                    if (pickerDateRange.startDate == null) {
                      startDateTEC.text = "";
                    } else {
                      startDateTEC.text =
                          pickerDateRange.startDate!.formatDateYYMMDD_HHMMSS();
                    }
                    if (pickerDateRange.endDate == null) {
                      endDateTEC.text = "";
                    } else {
                      endDateTEC.text = pickerDateRange.endDate!
                          .endOfToday()
                          .formatDateYYMMDD_HHMMSS();
                    }
                  }
                },
              ),
            ),
            10.heightBox,
            GFTextField(
              controller: startDateTEC,
              readOnly: true,
              decoration: const InputDecoration(
                border: OutlineInputBorder(
                  borderSide: BorderSide(width: 1, color: Colors.grey),
                ),
                contentPadding:
                    EdgeInsets.symmetric(horizontal: 3, vertical: 1),
                labelText: "开始时间",
              ),
            ),
            10.heightBox,
            GFTextField(
              controller: endDateTEC,
              readOnly: true,
              decoration: const InputDecoration(
                border: OutlineInputBorder(
                  borderSide: BorderSide(width: 1, color: Colors.grey),
                ),
                contentPadding:
                    EdgeInsets.symmetric(horizontal: 3, vertical: 1),
                labelText: "结束时间",
              ),
            ),
          ],
        ),
      ),
      actions: <Widget>[
        TextButton(
          child: const Text('关闭'),
          onPressed: () async {
            Navigator.of(context).pop();
          },
        ),
      ],
    );
  }
}
